/*
 * @Description: 向某条规则下添加用户、组弹窗
 * @Author: Rfan
 * @Date: 2022-04-08 09:07:14
 * @LastEditTime: 2022-04-26 11:45:47
 */

import { useCallback, useEffect } from 'react';
import { Button, message, Modal } from 'antd';
import type { FC } from 'react';
import {
  AddUserDialogContextProvider,
  useAddUserDialogContext
} from './contexts/AddUserDialogContext';
import { saveRoleUser } from '@/api/role';
import UserPane from './components/UserPane';
import type { ICommonDialog } from '@/interfaces/global';

interface IAddUserDialogProps extends ICommonDialog {
  roleId: number;
}

const AddUserDialogComp: FC<IAddUserDialogProps> = (props) => {
  console.log('AddUserDialogComp', props);

  const { visible, roleId, onClose } = props;
  const { selectUsers, setSelectUsers } = useAddUserDialogContext();
  const memoizedClose = useCallback((saveFlag = false) => {
    setSelectUsers([]);
    onClose(saveFlag);
  }, []);

  useEffect(() => {
    if (visible) {
      console.log('add', { visible, roleId });
    }
  }, [visible]);

  const onCancel = () => {
    memoizedClose();
  };

  const addUsers = () => {
    const userIdList = [...selectUsers];
    if (userIdList.length <= 0) {
      message.warning('请选择要添加的用户');
      return;
    }
    saveRoleUser({ roleId, userIdList }).then(() => {
      memoizedClose(true);
    });
  };

  return (
    <Modal
      title="选择人员"
      visible={visible}
      width={600}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          取消
        </Button>,
        <Button
          key="save"
          type="primary"
          onClick={() => {
            addUsers();
          }}
        >
          确认
        </Button>
      ]}
    >
      <UserPane />
    </Modal>
  );
};

const AddUserDialog = (props: any) => (
  <AddUserDialogContextProvider>
    {' '}
    <AddUserDialogComp {...props} />
  </AddUserDialogContextProvider>
);

export default AddUserDialog;
